﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using Universum.Infrastructure.Persistence;
using Universum.Infrastructure.Persistence.Queries.Classes;
using Universum.Model.Domain.Classes;
using Universum.Model.Services.MyClasses;
using StructureMap;
using System.Text;

namespace Universum.Model.Services.Classes
{
	public class LabWorkArticleServiceImpl : ILabWorkArticleService
	{
		IPrincipal _Principal;
		IFriendlyUrlService _FriendlyUrlService;
		IRepository _Repository;
		

		private ISubmissionService SubmissionService
		{
			get { return ObjectFactory.GetInstance<ISubmissionService>(); }
			
		}
		public LabWorkArticleServiceImpl(
			IPrincipal principal,
			IFriendlyUrlService slugService,
			IRepository repository//,
			//ISubmissionService submissionService
			)
		{
			_Principal = principal;
			_FriendlyUrlService = slugService;
			_Repository = repository;
			//_SubmissionService = submissionService;
		}

		#region ILabWorkArticleService Members

		public Universum.Model.Domain.Classes.LabWorkArticle CreateNewPageWork()
		{
			return new Universum.Model.Domain.Classes.LabWorkArticle
			{
				Created = DateTime.Now,
				ID = Guid.NewGuid(),
				Username = _Principal.Identity.Name
			};
		}

		public void SaveOrUpdate(Universum.Model.Domain.Classes.LabWorkArticle labWork)
		{
			var sb = new StringBuilder(labWork.ID.ToInt().ToString())
			.Append('-').Append(labWork.Title);
			labWork.Slug = _FriendlyUrlService.CreateSlugFrom(
				sb.ToString());
			_Repository.SaveOrUpdate(labWork);
		}

		public IList<Universum.Model.Domain.Classes.LabWorkArticle> GetLabWorkByPageGroupId(Guid guid)
		{
			
			return _Repository.Query(new LabWorkArticleByPageGroupId(guid))
				.OrderBy(it=>it.Publish)
				.ToList();
		}

		
		public LabWorkArticle GetLabWorkBySlug(string id)
		{
			return _Repository.Query(new LabWorkArticleBySlug(id)).FirstOrDefault();
		}
				
		public LabWorkArticle GetLabWorkArticleById(Guid guid)
		{
			return _Repository.Load<LabWorkArticle>(guid);
		}

		public void Remove(LabWorkArticle entity)
		{
			_Repository.Remove(entity);
		}

		public void RemoveByPageGroupId(Guid pageGroupId)
		{
			var labs = _Repository.Query(new LabWorkArticleByPageGroupId(pageGroupId));

			foreach (var lab in labs)
			{
				SubmissionService.RemoveByLabWorkId(lab.ID);
				_Repository.Remove(lab);
			}
		}

		#endregion
	}
}
